package com.zds.leetcode;

import java.util.Arrays;

public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode next;

    public TreeNode() {}

    public TreeNode(int _val) {
        val = _val;
    }

    public TreeNode(int _val, TreeNode _left, TreeNode _right, TreeNode _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }

    public static void printTreeNode(TreeNode root) {
        int height = getHeight(root);
        String[][] res = new String[height][(1 << height) - 1];

        for (String[] arr : res) {
            Arrays.fill(arr, "   ");
        }

        fill(res, root, 0, 0, res[0].length);
        for (String[] arr : res) {
            for (String s : arr) {
                System.out.print(s);
            }
            System.out.println();
        }
        System.out.println("============");
    }

    private static void fill(String[][] res, TreeNode node, int row, int i, int j) {
        if (node == null) {
            return;
        }
        res[row][(i + j) / 2] = String.format("%3d", node.val);
        fill(res, node.left, row + 1, i, (i + j) / 2);
        fill(res, node.right, row + 1, (i + j + 1) / 2, j);
    }

    private static int getHeight(TreeNode node) {
        if (node == null) {
            return 0;
        }
        return 1 + Math.max(getHeight(node.left), getHeight(node.right));
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.right = new TreeNode(6);

        printTreeNode(root);
    }
}
